#include "acq_task.h"

namespace iot_acq {
#define TASK_MAX_TIMES (13)
std::vector<int32_t> PRIME_NUMBER = {
	0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 720};

bool AcqTask::IsInRetry(int32_t times)
{
	if (std::find(PRIME_NUMBER.begin(), PRIME_NUMBER.end(), times) !=
		PRIME_NUMBER.end()) {
		return true;
	}
	if (times % 720 == 0) {
		return true;
	}
	return false;
}

void AcqTask::OnTimerTask()
{
	for (auto &pair : mapRpc_) {
		std::shared_ptr<leoyun::YunRpc> rpc = pair.second;
		if (rpc == nullptr) {
			HTELINK_LOG_INFO("sth error about %s", pair.first.c_str());
			continue;
		}
		if (!rpc->IsRun() && !IsInRetry(rpc->Times()++)) {
			continue;
		}
		rpc->Run();
		if (rpc->IsRun()) {
			rpc->Times() = 0;
		}
	}
}

AcqTask::AcqTask()
	: vendor::VendorIf([&]() { OnTimerTask(); })
{
}
void AcqTask::PushRpc(const std::string& name,
                      std::shared_ptr<leoyun::YunRpc> rpc) {
	mapRpc_.insert(
		std::pair<std::string, std::shared_ptr<leoyun::YunRpc> >(name, rpc));
}
void AcqTask::ForEach(
	const std::function<void(const std::shared_ptr<leoyun::YunRpc> &)> &rpcCall)
{
	for (auto &pair : mapRpc_) {
		std::shared_ptr<leoyun::YunRpc> rpc = pair.second;
		if (rpc == nullptr) {
			HTELINK_LOG_INFO("sth error about %s", pair.first.c_str());
			continue;
		}
		rpcCall(rpc);
	}
}
}  // namespace iot_acq
